package com.iseastar.guojiang.passport;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.newcabinet.BikingRouteOverlay;
import com.shouhuobao.station.R;

import static droid.frame.utils.lang.Str.isNotEmpty;

/**
 * Created by joker on 2017/12/25.
 * passport地图
 */
public class PassportTaskMapFragment extends BaseFragment implements BDLocationListener {

    // 定位相关
    private LocationClient mLocClient;

    private BaiduMap mBaiduMap;
    private TextureMapView mMapView = null;
    private PlanNode sNode = null;
    private PlanNode eNode = null;
    private RoutePlanSearch mSearch;
    private ServiceTaskBean serviceTaskBean = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (null != bundle) {
            serviceTaskBean = (ServiceTaskBean) bundle.getSerializable("item");
            if (serviceTaskBean != null) {
                // 定位初始化
                mLocClient = new LocationClient(getActivityContext());
                mLocClient.registerLocationListener(this);
                LocationClientOption option = new LocationClientOption();
                option.setIsNeedAddress(true);// 设置以后,请求结果 BDLocation#getCity 就不为null了
                option.setOpenGps(true);// 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setScanSpan(0);// 定位频率
                mLocClient.setLocOption(option);
                mLocClient.start();
            }
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.passport_task_map);
        super.findViewById();
        mMapView = (TextureMapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        mBaiduMap.setMyLocationEnabled(true);
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
        mMapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    mMapView.getParent().requestDisallowInterceptTouchEvent(false);
                } else { //不允许ScrollView截断点击事件，点击事件由子View处理
                    mMapView.getParent().requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    private void routeplanToNavi(double lat, double lng) {
        mBaiduMap.clear();
        if (Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
            makeMarker(lat, lng);
            LatLng northeast = new LatLng(Math.max(serviceTaskBean.getGiveLatitude(), serviceTaskBean.getLatitude()), Math.max(serviceTaskBean.getGiveLongitude(), serviceTaskBean.getLongitude()));
            LatLng southwest = new LatLng(Math.min(serviceTaskBean.getGiveLatitude(), serviceTaskBean.getLatitude()), Math.min(serviceTaskBean.getGiveLongitude(), serviceTaskBean.getLongitude()));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdateFactory.newLatLngBounds(bounds);
            sNode = PlanNode.withLocation(new LatLng(serviceTaskBean.getLatitude(), serviceTaskBean.getLongitude()));
            eNode = PlanNode.withLocation(new LatLng(serviceTaskBean.getGiveLatitude(), serviceTaskBean.getGiveLongitude()));
        } else {
            LatLng northeast = new LatLng(Math.max(lat, serviceTaskBean.getLatitude()), Math.max(lng, serviceTaskBean.getLongitude()));
            LatLng southwest = new LatLng(Math.min(lat, serviceTaskBean.getLatitude()), Math.min(lng, serviceTaskBean.getLongitude()));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdateFactory.newLatLngBounds(bounds);
            sNode = PlanNode.withLocation(new LatLng(lat, lng));
            eNode = PlanNode.withLocation(new LatLng(serviceTaskBean.getLatitude(), serviceTaskBean.getLongitude()));
        }
        if (sNode != null && eNode != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mSearch.bikingSearch((new BikingRoutePlanOption()).from(sNode).to(eNode));
                }
            }).start();
            //            mSearch.drivingSearch((new DrivingRoutePlanOption()).from(sNode).to(eNode));
        }
    }

    /**
     * 同城添加地图上marker，标记我的位置
     *
     * @return
     */
    public Marker makeMarker(double lat, double lng) {
        LatLng llB = new LatLng(lat, lng);
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.passport_my_icon);
        OverlayOptions ooB = new MarkerOptions().position(llB).icon(bitmap).zIndex(9).draggable(true);
        Overlay overlay = mMapView.getMap().addOverlay(ooB);
        Marker marker = (Marker) (overlay);
        return marker;
    }

    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult result) {
            //获取步行线路规划结果
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult result) {
            //获取公交换乘路径规划结果
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
            //获取驾车线路规划结果
            //                        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            //                            showToast("抱歉，未找到结果");
            //                        }
            //                        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //                            //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            //                            //result.getSuggestAddrInfo()
            //                            return;
            //                        }
            //                        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            //                            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
            //                            //            mBaidumap.setOnMarkerClickListener(overlay);
            //                            overlay.setData(result.getRouteLines().get(0));
            //                            overlay.addToMap();
            //                            overlay.zoomToSpan();
            //                        }
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                //result.getSuggestAddrInfo()
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
                //            mBaidumap.setOnMarkerClickListener(overlay);
                overlay.setData(bikingRouteResult.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();

            }
        }
    };

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation == null) {
            showToast("定位失败");
        } else {
            String currentCityName = bdLocation.getCity();
            if (isNotEmpty(currentCityName)) {
                routeplanToNavi(bdLocation.getLatitude(), bdLocation.getLongitude());
            } else {
                showToast("定位失败");
            }
        }
    }

    private class MyBikingRouteOverlay extends BikingRouteOverlay {
        /**
         * 构造函数
         *
         * @param baiduMap 该DrivingRouteOvelray引用的 BaiduMap
         */
        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            //覆写此方法以改变默认起点图标
            if (serviceTaskBean != null && Const.CourierTaskStatus.sameCityTask == serviceTaskBean.getTaskType()) {
                return BitmapDescriptorFactory.fromResource(R.drawable.passport_task_send_icon);
            } else {
                return BitmapDescriptorFactory.fromResource(R.drawable.passport_my_icon);
            }
            //这里可以使用BitmapDescriptorFactory.fromView(view)实现自定义view覆盖物，自定义覆盖物请关注以后的文章。
        }

        @Override
        public Integer getLineColor() {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认绘制颜色
            //Returns:
            //线颜色
            return super.getLineColor();
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            //覆写此方法以改变默认终点图标
            return BitmapDescriptorFactory.fromResource(R.drawable.passport_take_icon);
        }

        @Override
        public boolean onRouteNodeClick(int i) {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认点击处理
            return true;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mSearch != null) {
            mSearch.destroy();
        }
        if (mBaiduMap != null) {
            mBaiduMap.clear();
        }
        if (mSearch != null) {
            mSearch.destroy();
        }
        mMapView.onDestroy();
        mLocClient.stop();
        super.onDestroy();
    }
}
